import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.util.Vector;

import java.io.*;
import java.rmi.*;

public class ChatServer extends UnicastRemoteObject implements ChatServerInt {
	// vector que almacena los clientes conectados
	private Vector<ChatClientInt> clients = new Vector<ChatClientInt>();
	private IncreaseNumMessages service;	
	public static final char LF = '\n';
	public static final char CR = '\r';	
	
	
	public ChatServer() throws RemoteException {
		FindRemoteIncNumOfMess();
	}

	// metodo para registrarse en el chat
	public boolean login(ChatClientInt client) throws RemoteException {
		service.setServerAlive(true);
		System.out.println("Login: " + client.getName());
		Message m = new Message("Se ha conectado al chat.");
		client.message(m);
		clients.add(client);
		for (int index = 0; index < clients.size(); ++index) {   //alvaro
			try {
				ChatClientInt tmpClient = (ChatClientInt) clients.get(index);
				tmpClient.updateUsers(clients);
			} catch (Exception e) {
			}
		}
		return true;
	}
	
	// metodo para desconectarse en el chat
	public boolean logout(ChatClientInt client) throws RemoteException {  //alvaro
		System.out.println("Logout: " + client.getName());
		clients.remove(client);
		for (int index = 0; index < clients.size(); ++index) {
			try {
				ChatClientInt tmpClient = (ChatClientInt) clients.get(index);
				tmpClient.removeUser(client.getName());
			} catch (Exception e) {
			}
		}
		client.removeUser(client.getName());
		return true;
	}
	
	public boolean getServerAlive() //@PEDRO
	{
		try
		{
			return service.getServerAlive();
		}
		catch (RemoteException re) {}
		return false;
	}

	// enviar un mensaje a todos los clientes conectados al chat
	public void sendToAll(String text) throws RemoteException {
		System.out.println("SendToAll: " + text);
		
		try {	//@PEDRO
			int num = service.increaseNumberOfMessages();
			System.out.println("Number of messages: "+ num);   //@PEDRO
			
			for (int index = 0; index < clients.size(); ++index) {
				try {
					ChatClientInt tmpClient = (ChatClientInt) clients.get(index);
					Message m = new Message(text, num);
					tmpClient.message(m);
				} catch (Exception e) {
				}
			}
		}   //@PEDRO
		catch (Exception e) {System.out.println("Error on sendToAll- " + e);}	//@PEDRO	
	}

	// obtener los clientes conectados al servidor
	public Vector getConnected() throws RemoteException {
		return clients;
	}

	// revisa si el server esta vivo
	public boolean AreYouAlive(ChatClientInt a) throws RemoteException {  //@PEDRO
		try
		{
			service.setServerAlive(true);
		}
		catch (RemoteException re) {}
		return true;
	}
	
	public void FindRemoteIncNumOfMess(){
		String string="";
	    String file ="IP.txt";
		String line="";
	
		try{
			File f = new File(file);
	        	if(f.exists() && !f.isDirectory()) { 
	        		InputStream ips=new FileInputStream(f); 
	                InputStreamReader ipsr=new InputStreamReader(ips);
	                BufferedReader br=new BufferedReader(ipsr);
	                while ((line=br.readLine())!=null){                
	                    //string+=line+"\n";
	                    break;
	                }
	                //numMessages = Integer.parseInt(line);
	                br.close();
				}
		
		
			//String registry = "localhost";
			//String registry = StringUtils.chomp(line);
		  int lastIdx = line.length() - 1;
		  char last = line.charAt(lastIdx);

		  if (last == LF) {
			  if (line.charAt(lastIdx - 1) == CR) {
				  lastIdx--;
			  }
		  } else if (last != CR) {
			  lastIdx++;
		  }
		  String registry = line.substring(0, lastIdx);			
			
			/*
			if(args.length >=1 ){
				registry = args[0];
			}
			*/
			
			String registration = "rmi://" + registry + "/IncreaseNumMessages";
			Remote remoteService = Naming.lookup(registration);
			service = (IncreaseNumMessages) remoteService;
			//IncreaseNumMessages service = (IncreaseNumMessages) remoteService;
			//System.out.println("Number of messages : " + service.increaseNumberOfMessages());
			
		}
		catch(NotBoundException nbe) { System.out.println("No IncreaseNumMessages service available in registry!");}
		catch (RemoteException re) {System.out.println("RMI Error - " + re);}
		catch (Exception e) {System.out.println("Error - " + e);}
	} 
}	